package cvo.chess.client.entities;

import java.util.ArrayList;
import java.util.List;

import cvo.chess.client.entities.armies.Piece;
import cvo.chess.client.entities.chessboard.ChessboardCoordinate;
import cvo.chess.client.entities.chessboard.Tile;
import cvo.chess.client.entities.game.IChessboard;

public class GameFacade {	
	
	private static List<GameFacade> instances = new ArrayList<GameFacade>();
	
	public static GameFacade get(){
		//TODO: generate id
		GameFacade gf = new GameFacade(0);
		instances.add(gf);
		return gf;
	}
	
	public static GameFacade get(Integer id){
		for(GameFacade gf : instances){
			if(gf.id.equals(id)){
				return gf;
			}
		}
		return null;
	}
	
	private Integer id; 
	private Game game;
	
	protected GameFacade(Integer id)
	{
		this.id = id;
	}
	
	
	public Game newGame(){
		Game g = new Game(this);
		this.game = g;
		return g; 
	}

	public IChessboard getBoard() {		
		return this.game.getBoard();
	}

	public void startGame() throws Exception {
		this.game.Init();
		this.game.Start();		
	}

	public Piece getPieceAt(ChessboardCoordinate boardCoordinate) {		
		return this.game.findPieceAt(boardCoordinate);
	}

	public void setPieceAtPosition(Piece piece, ChessboardCoordinate position) throws Exception {
		this.game.setPiece(piece, position);
	}

	public Tile getTileAt(String a1notation) {
		return this.getBoard().getTileAt(new ChessboardCoordinate(this.getBoard(), a1notation));
	}

	public Piece getPieceAt(String a1notation) {
		return this.game.findPieceAt(new ChessboardCoordinate(this.getBoard(), a1notation));
	}

	public void doMove(String from, String to) throws Exception {
		//TODO: never trust your gui... so, validate input again
		//Throw exception when not valid. You may 'punish' the gui for bad input validation 
		ChessboardCoordinate fromBc = new ChessboardCoordinate(getBoard(), from);
		ChessboardCoordinate toBc = new ChessboardCoordinate(getBoard(), to);
		
		this.game.doMove(fromBc, toBc);
		
	}	
	
	
	
	
}
